package lib.api.bierdopje;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import util.Downloader;

import lib.XML.XMLHelper;
import lib.api.bierdopje.model.JBierSubtitle;

public class JBierdopjeRSS {
	
	public JBierdopjeRSS(){
		
	}
	
	public List<JBierSubtitle> searchRSS(String filename, int showid, String show,
			int season, List<Integer> episodeNumbers, String languagecode) throws MalformedURLException, IOException, BierdopjeException, ParserConfigurationException, SAXException {
		List<JBierSubtitle> lSubtitles = new ArrayList<JBierSubtitle>();
		Document doc = getRssDocument(languagecode);
		NodeList nList = doc.getElementsByTagName("item");
		for (int i = 0; i < nList.getLength(); i++) {
            if (nList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nList.item(i);
                String rssFilename = XMLHelper.getStringTagValue("title", eElement);
                int rssShowid = XMLHelper.getIntTagValue("show_id", eElement);
                String rssShow = XMLHelper.getStringTagValue("showname", eElement);
                int rssSeason = XMLHelper.getIntTagValue("season", eElement);
                int rssEpisode = XMLHelper.getIntTagValue("episode", eElement);
                if (showid == rssShowid 
                		&& show.equalsIgnoreCase(rssShow) 
                		&& season == rssSeason 
                		&& episodeNumbers.get(0) == rssEpisode){
                	JBierSubtitle subtitle = new JBierSubtitle();
                    subtitle.setFilename(rssFilename);
                    subtitle.setDownloadlink(XMLHelper.getStringAtributeValue("enclosure", "url", eElement));
                    subtitle.setUploader(XMLHelper.getStringTagValue("uploader", eElement));
                    lSubtitles.add(subtitle);
                }
            }
		}
		return lSubtitles;
	}
	
	protected Document getRssDocument(String languagecode) throws MalformedURLException, IOException, BierdopjeException, ParserConfigurationException, SAXException{
		URLConnection conn;
		if (languagecode.equalsIgnoreCase("nl")){
			conn = new URL("http://external.bierdopje.com/subtitles/BDUSR973C35F9BA0E4D5AF45/nl/").openConnection();
		}else if (languagecode.equalsIgnoreCase("en")){
			conn = new URL("http://external.bierdopje.com/subtitles/BDUSR973C35F9BA0E4D5AF45/en/").openConnection();
		}else{
			throw new BierdopjeException("Unknown language code", languagecode);
		}
	    conn.setReadTimeout(2000);
	    return XMLHelper.getDocument(Downloader.getUrlContents(conn));
	}
}
